﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Common.Utilities;
using MediatR;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NLog;

namespace Casamiel.API.Infrastructure.Behaviors
{
    /// <summary>
    /// Logging behavior.
    /// </summary>
    public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    {
        private readonly NLog.ILogger _logger = LogManager.GetLogger("LoggingBehavior");
        //private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
        {
        }//=> _logger = logger;
        /// <summary>
        /// Handle the specified request, cancellationToken and next.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <param name="next">Next.</param>
        public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
        {
            //_logger.Trace($"Handling {typeof(TRequest).Name}");
            var begin = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            var response = await next().ConfigureAwait(false);
            var end = DatetimeUtil.GetUnixTime(DateTime.Now, TimePrecision.Millisecond);
            if(end - begin > 200)
            {
                _logger.Trace($"Handle:{typeof(TRequest).Name},req:{JsonConvert.SerializeObject(request)}, {typeof(TResponse).Name},rsp:{JsonConvert.SerializeObject(response)},执行时间{end - begin}毫秒");
            }
            return response;

        }
    }
}
